package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class UserLikeApiImpl implements UserLikeApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Boolean saveOrUpdate(Long userId, Long likeUserId, boolean isLike) {
        try {
            Query query = Query.query(Criteria.where("userId").is(userId)
                    .and("likeUserId").is(likeUserId));
            UserLike one = mongoTemplate.findOne(query, UserLike.class);
            if(one==null){
                one=new UserLike();
                one.setUserId(userId);
                one.setLikeUserId(likeUserId);
                one.setIsLike(isLike);
                one.setUpdated(System.currentTimeMillis());
                one.setCreated(System.currentTimeMillis());
                mongoTemplate.save(one);
            }else {
                Update update=Update.update("isLike",isLike).set("updated",System.currentTimeMillis());
                mongoTemplate.updateFirst(query,update,UserLike.class);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    //我喜欢的
    @Override
    public List<UserLike> likeList(Long userId,Boolean isLike) {
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("isLike").is(isLike));
        List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);
        return userLikes;
    }

    @Override
    public UserLike toUserLike(Long userId, Long likeUserId,Boolean isLike) {
        Query query = Query.query(Criteria.where("userId").is(likeUserId)
                .and("likeUserId").is(userId)
                .and("isLike").is(isLike));
        UserLike userLike = mongoTemplate.findOne(query, UserLike.class);
        return userLike;
    }

    @Override
    public void deleteLike(Long userId, Long uid) {
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("likeUserId").is(uid));
        mongoTemplate.remove(query,UserLike.class);
    }
}
